#!/usr/bin/env python

__author__ = 'rx.wen218@gmail.com'

import gdata.service
import gdata.blogger.client
import xmlrpclib
import postconverter
import logging
from datetime import datetime

MAX_POSTS_NUM = 9999

class BloggerProvider:
    def __init__(self, user_name, password, post_converter = postconverter.BloggerPostConverter()):
        self.logger = logging.getLogger(__name__)
        self.gclient = gdata.blogger.client.BloggerClient()
        self.gclient.ClientLogin(user_name, password, "blogporter_application")
        self.user_name = user_name
        self.password = password
        self.blogs = self.gclient.GetBlogs()
        self.blog_id = self.blogs.entry[0].get_blog_id()
        self.post_converter = post_converter
        
        self.blogger_service = gdata.service.GDataService(user_name, password, account_type = "GOOGLE", service = "blogger", source = "blogporter_application", server="www.blogger.com")
        self.blogger_service.ProgrammaticLogin()

    def GetPosts(self, max_posts_num = MAX_POSTS_NUM, start_date = None, end_date = None):
        # http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.client.html#Query
        # query = gdata.blogger.client.Query(updated_min=start_time, updated_max=end_time, order_by='updated')
        if start_date:
            start_date_str = start_date.strftime("%Y-%m-%dT%H:%M:%S+08:00")
        if end_date:
            end_date_str = end_date.strftime("%Y-%m-%dT%H:%M:%S+08:00")

        query = gdata.blogger.client.Query(max_results=max_posts_num, order_by='published', published_min=start_date_str, published_max=end_date_str)
        blogger_posts = self.gclient.GetPosts(self.blog_id, query=query)

        posts = [self.post_converter.GetGenericPost(post) for post in blogger_posts.entry]
        return posts

    def AddPost(self, post):
        # gdata.blogger.client.BloggerClient.AddPost method doesn't allow us specify post time
        # so, use lower level api instead
        # self.gclient.AddPost(self.blog_id, title, content, body_type='html')
        new_post = self.post_converter.GetSpecificPost(post)
        self.blogger_service.Post(new_post, '/feeds/' + self.blog_id + '/posts/default')

    def UpdatePost(self, post):
        post_to_update = None
# post.create_date doesn't include timezone info, so take a full day's timezone range into consideration
        published_min = '%s+12:59' % post.create_date.strftime('%Y-%m-%dT%H:%M:%S.%f')
        published_max = '%s-12:59' % post.create_date.strftime('%Y-%m-%dT%H:%M:%S.%f')
        query = gdata.blogger.client.Query(published_min = published_min, published_max = published_max)
        blogger_posts = self.gclient.GetPosts(self.blog_id, query=query)
        for p in blogger_posts.entry:
            if post.postid == p.id.text:
                post_to_update = p
                break
        if None != post_to_update:
            post_to_update.content.text = post.content
            post_to_update.title.text = post.title
            self.gclient.Update(post_to_update)

    def DeleteAllPosts(self):
        query = gdata.blogger.client.Query(max_results=MAX_POSTS_NUM, order_by='published')
        posts = self.gclient.GetPosts(self.blog_id, query=query)
        for post in posts.entry:
            self.gclient.Delete(post)
